package com.dispatcher;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dispatcher.bean.Order;
import com.dispatcher.bean.UserOrders;
import com.dispatcher.common.OrderSort;
import com.dispatcher.helper.SDHelper;
import com.dispatcher.http.HttpHelperWraper;
import com.dispatcher.http.HttpHelperWraper.HttpRequestParam;
import com.dispatcher.http.HttpHelperWraper.OnNetListener;
import com.dispatcher.view.PullRefreshHitMoreListView;
import com.dispatcher.view.PullRefreshHitMoreListView.OnRefreshRequestListener;
import com.zuzhili.database.CacheDataCtrl;
import com.zuzhili.database.CacheDataCtrl.CacheType;

public class MyOrderActivity extends ActivityBase implements OnNetListener, OnItemClickListener {
	private String GET_TASK_ORDER = "getMyPickOrder";
	private final int FLAG_TO_GIFT_ACTIVITY = 0;
	private final int FLAG_TO_REPORT_STATUS = 1;
	private LayoutInflater mInflater;
	private List<Order> userOrderList;
	private OrderAdapter orderAdapter;
	private String giftid;
	private String presentid;
	private Button btOnClick;
	private PullRefreshHitMoreListView  lvOrderList;
	
	private int start = 0;
	private int count = 50;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_order);
		GET_TASK_ORDER=getIntent().getStringExtra("task");
		
		lvOrderList = (PullRefreshHitMoreListView) findViewById(R.id.lv_orderlist);
		orderAdapter = new OrderAdapter();
		userOrderList = new ArrayList<Order>();
		lvOrderList.setAdapter(orderAdapter);
		lvOrderList.setOnItemClickListener(this);
		lvOrderList.setonRefreshListener(new OnRefreshRequestListener() {
			
			@Override
			public void onRefresh() {
				start = 0;
//				orderList.clear();
				lvOrderList.changeToOnRefresh();
				sendRequest(GET_TASK_ORDER, start);
			}
		});
		presentid = SDHelper.getPresentId();
		lvOrderList.changeToOnRefresh();
		sendRequest(GET_TASK_ORDER, start);
		
		start += count;
		
		mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}
	
	void sendRequest(String action, int start) {
		HttpHelperWraper http = new HttpHelperWraper();
		HttpRequestParam param = http.getParam();
		makeparam(param, action, start);
		http.AsyncTaskWithCache(param);
	}
	
	void makeparam(HttpRequestParam param, String action, int start){
		if (param == null) {
			return;
		}
		param.ctx = this;
		param.listener = this;
		param.activitybase=this;
		if(GET_TASK_ORDER.equals("getMyPickOrder")){
			
			param.cachetype=CacheDataCtrl.CacheType.MyOrders_Cache;
			param.identify="mypick";
		}else if(GET_TASK_ORDER.equals("getSendedOrder")){
			
			param.cachetype=CacheDataCtrl.CacheType.SendedOrders_Cache;
			param.identify="sended";
		} 
		param.expiretime=0;
		HashMap<String, Object> requestparams = new HashMap<String, Object>();
		if(action.equals(GET_TASK_ORDER)) {
			requestparams.put("task", GET_TASK_ORDER);
			requestparams.put("presentid", presentid);
			requestparams.put("begin", start + "");
			requestparams.put("count", count + "");
		}
		param.nodesrequest = requestparams;
	}
	
	@Override
	public void onNetSuccess(HttpRequestParam param) {
//		Log.i("liutao", param.nodesrequest.toString());
//		Log.i("liutao", param.nodesresult.toString());
//		JSONObject nodesresult = param.nodesresult;
//		JSONArray jsonArray = null;
//		if(nodesresult.has("list")) {
//			try {
//				jsonArray = (JSONArray) nodesresult.get("list");
//			} catch (JSONException e) {
//				e.printStackTrace();
//			}
//		}
		com.alibaba.fastjson.JSONObject obrst=JSON.parseObject(param.jsonstr);
		
		List<UserOrders> l = JSON.parseArray(obrst.getString("list"), UserOrders.class);
		if(param.nodesrequest.get("begin").equals("0")){
			userOrderList.clear();
			
		}
		;
		userOrderList.addAll(collectOrders(l));
		
		Collections.sort(userOrderList, new OrderSort().getOneOrderSort());
		
		orderAdapter.notifyDataSetChanged();
		
		if(param.bendreq) {
			lvOrderList.onPullRefreshEnd();
			
			if (l.size() == 0) {
				Toast.makeText(getApplicationContext(), "没有更多了",
						Toast.LENGTH_SHORT).show();
				lvOrderList.onFooterRefreshEnd(true);
				lvOrderList.onFooterHide();
			} else {
				lvOrderList.onFooterRefreshEnd(false);
			}
			
		}
		
	}

	@Override
	public void onNetError(HttpRequestParam param) {
		Toast.makeText(this, param.rstmsg, 2000).show();
	}
	List<Order> collectOrders(List<UserOrders> userorderlist){
		List<Order> rstlist=new ArrayList<Order>();
		for(UserOrders user:userorderlist){
			rstlist.addAll(user.getOrders());
		}
		
		return rstlist;
	}
	OnClickListener leftlis = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			
		}
	};
	
	OnClickListener rightlis = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
		}
	};
	
	public class OrderAdapter extends BaseAdapter {

		@Override
		public int getCount() {
			return userOrderList.size();
		}

		@Override
		public Object getItem(int arg0) {
			return userOrderList.get(arg0);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final int pos = position;
			ViewHolder holder;
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.order_item, null);
				holder.homeRegion = (TextView) convertView
						.findViewById(R.id.tv_home_region);

//				holder.count = (TextView) convertView
//						.findViewById(R.id.tv_count);
				holder.goodsName = (TextView) convertView.findViewById(R.id.tv_goods_name);
//				holder.address = (TextView) convertView
//						.findViewById(R.id.tv_address);
				holder.pickOrder = (Button) convertView.findViewById(R.id.bt);
//				holder.unitNo = (TextView) convertView.findViewById(R.id.tv_unit_no);
//				holder.buildingNo = (TextView) convertView.findViewById(R.id.tv_building_no);
				holder.phone = (TextView) convertView.findViewById(R.id.tv_phone);
				holder.needpay = (TextView) convertView.findViewById(R.id.tv_needpay);
				holder.time = (TextView) convertView.findViewById(R.id.tv_time);
				
				final Button tempButton = holder.pickOrder;
				
				holder.pickOrder.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						// task modifyOrderState presentid orderid status giftid goodid goodtype
						btOnClick = tempButton;
//						orderList.get(pos).setGiftSelected(true);
						Intent it = new Intent(MyOrderActivity.this, GiftActivity.class);
						Order order = userOrderList.get(pos);
						it.putExtra("orderid", order.getOrderid());
						it.putExtra("presentid", SDHelper.getPresentId());
						
						startActivityForResult(it, FLAG_TO_GIFT_ACTIVITY);
					}
				});
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
//			UserOrders userorders = userOrderList.get(position);
//			String name="";
//			float needpay=0;
//			for(Order ord:userorders.getOrders()){
//				name+=ord.getName()+" "+ord.getGoodtype()+" X "+ord.getCount()+"\n";
//				needpay+=Float.valueOf(ord.getNeedpay());
//			}
//			holder.goodsName.setText(name);
//			holder.time.setText(userorders.getTime());
//			holder.homeRegion.setText(userorders.getRegion()+" "+userorders.getName());
//			holder.phone.setText(userorders.getPhone());
//			holder.needpay.setText(String.valueOf(needpay));
			
			Order item=userOrderList.get(position);
			holder.goodsName.setText(item.getName()+" "+item.getGoodtype()+" X "+item.getCount());
			holder.time.setText(item.getCreatetime());
			String orderaddress = item.getOrderaddress();
			if(orderaddress==null || orderaddress.length()==0 ||orderaddress.equals("null")){
				orderaddress=item.getRegion()+" "+item.getBuilding();
			}
			holder.homeRegion.setText(orderaddress+" "+(item.getSendername()==null?"":item.getSendername()));
			holder.phone.setText(item.getPhone());
			holder.needpay.setText(String.valueOf(item.getNeedpay()));
			
			if(item.isGiftSelected()){
				holder.pickOrder.setText(item.getGiftname());
				holder.pickOrder.setClickable(false);
			}else{
				holder.pickOrder.setClickable(true);
				holder.pickOrder.setText("选取赠品");
			}
			return convertView;
		}
		
	}
	
	class ViewHolder {
		TextView homeRegion;
		TextView unitNo;
		TextView buildingNo;
		TextView count;
		TextView needpay;
		TextView goodsName;
		TextView address;
		TextView phone;
		Button pickOrder;
		TextView time;
	}


	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if(arg2 == arg0.getCount() - 1) {
			if (lvOrderList.onFooterRefreshBegin()) {
				sendRequest(GET_TASK_ORDER, start);
			}
			return;
		}
		
		Order userorders = userOrderList.get(arg2 - 1);
		if(!userorders.isGiftSelected()) {
			Toast.makeText(this, "请先选择赠品", Toast.LENGTH_SHORT).show();
			return;
		}
			
//		String orderId = userorders.getOrderid();
//	    String presentId = SDHelper.getPresentId();
//	    String goodid = userorders.getGoodid();
//	    String goodtype = userorders.getGoodtype();
//	    String phone = userorders.getPhone();
//	    
//	    Intent it = new Intent();
//	    it.putExtra("orderid", orderId);
//	    it.putExtra("presentid", presentId);
//	    it.putExtra("giftid", userorders.getGiftid());
//	    it.putExtra("goodid", goodid);
//	    it.putExtra("goodtype", goodtype);
//	    it.putExtra("phone", phone);
	    
		Intent it = new Intent();
	    Bundle bundle = new Bundle();
	    bundle.putSerializable("userorders", userOrderList.get(arg2-1));
	    it.putExtras(bundle);
	    
	    it.setClass(this, ReportStatusActivity.class);
	    startActivityForResult(it, FLAG_TO_REPORT_STATUS);
	    
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode == FLAG_TO_GIFT_ACTIVITY) {
			if(data != null) {
				String giftName = data.getStringExtra("name");
				giftid = data.getStringExtra("giftid");
				String orderid=data.getStringExtra("orderid");
//				for(UserOrders item:userOrderList){
					for(Order ord:userOrderList){
						
						if(ord.getOrderid().equals(orderid)){
							ord.setGiftname(giftName);
							ord.setGiftid(giftid);
							break;
						}
					}
//				}
				
				btOnClick.setText(giftName);
				btOnClick.setClickable(false);
			}
			
		} else if(requestCode == FLAG_TO_REPORT_STATUS) {
//			orderList.clear();
			if(resultCode==Activity.RESULT_OK){
				
				String orderid=data.getStringExtra("orderid");
				for(Order item:userOrderList){
					if(item.getOrderid().equals(orderid)){
						userOrderList.remove(item);
						orderAdapter.notifyDataSetChanged();
						HttpHelperWraper http = new HttpHelperWraper();
						http.clearCache(this, CacheType.MyOrders_Cache, "mypick");
						break;
					}
				}
			}
			
//			sendRequest(GET_MYPICK_ORDER, 0);
		}
	}
	class Sort_Orders implements Comparator<UserOrders> {

		@Override
		public int compare(UserOrders item1, UserOrders item2) {
			boolean object1 = item1.isGiftSelected();
			boolean object2 = item2.isGiftSelected();
			int ret = (!object1)?-1:1;
			return ret;
		}

	}

}
